package com.core.config;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Author: 孙常胜
 * @CreateTime: 2021/7/21 14:51
 * @Description:客户端
 */
@Log4j2
@Component
public class Client {
    @Value("${netty.server.host}")
    private String host;
    @Value("${netty.server.port}")
    private int port;

    public void connectServer() {
        //netty通过ServerBootstrap启动服务端
        Bootstrap bootstrap = new Bootstrap();
        //第1步 定义线程组，处理读写和链接事件，没有了accept事件
        EventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group);
        //第2步 绑定客户端通道
        bootstrap.channel(NioSocketChannel.class);
        //第3步 给NIoSocketChannel初始化handler， 处理读写事件
        //通道是NioSocketChannel
        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
//                ChannelPipeline pipeline = nioSocketChannel.pipeline();
//                pipeline.addLast("decoder", new StringDecoder());
//                pipeline.addLast("encoder", new StringEncoder());
                //找到管道 增加handler
                nioSocketChannel.pipeline().addLast(new ClientHandler());
            }
        });
        try {
            //连接服务器
            ChannelFuture future = bootstrap.connect(host, port).sync();
            //此处连接上服务端就发送信息

            //当通道关闭了，就继续往下走
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("客户端连接服务器-----异常---" + e);
            e.printStackTrace();
        } finally {
            //优雅停机
            group.shutdownGracefully();
        }
    }

    public static byte[] hexString2Bytes(String src) {
        int l = src.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            ret[i] = (byte) Integer.valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
        }
        return ret;
    }


}
